package org.example.java.jvm.monitoring;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * -Xms100M -Xmx100M -XX:+PrintGCDetails
 */
public class MonitorTest {
  static class OOMObject {
    public byte[] placeholder = new byte[64 * 1024];

    public OOMObject run() {
      return this;
    }
  }

  private static void fillHeap(int num, BufferedReader bufferedReader) throws InterruptedException, IOException {
    int i = 0;
    List<OOMObject> list = new ArrayList<OOMObject>();
    try {
      while (i++ < num) {
        TimeUnit.MILLISECONDS.sleep(150);
        list.add(new OOMObject().run());
      }
      System.gc();//不能收回
      bufferedReader.readLine();
    } finally {
      System.out.println(i);
    }
  }


  /**
   * 死循环线程
   */
  private static void createBusyThread() {
    Thread thread = new Thread(new Runnable() {
      @Override
      public void run() {
        while (true)
          ;
      }
    }, "testBusyThread");
    thread.start();
  }

  public static void createLockThread(final Object lock) {
    new Thread("testLockThread") {
      public void run() {
        synchronized (lock) {
          try {
            lock.wait();
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
      }
    }.start();
  }

  public static void main(String[] args) throws InterruptedException, IOException {
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));

    fillHeap(1000, bufferedReader);
//    bufferedReader.readLine();
//    System.gc();  //能回收

//   bufferedReader.readLine();
//    createBusyThread();
//    bufferedReader.readLine();
//    createLockThread(new Object());
  }
}
